package com.durian.base.update.ui

import android.content.Intent
import com.durian.base.frame.activity.ActivityFrame
import com.durian.base.permission.RequestExecutor
import com.durian.base.permission.SoonPermission
import com.durian.base.permission.listener.SimplePermissionListener
import com.durian.base.permission.task.IPermissionTask
import com.durian.ui.dialog.DialogAlert
import java.io.File

/**
 * 说明：ActivityDefaultInstaller
 * <p/>
 * 作者：fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2021/1/22 23:10
 * <p/>
 * 版本：version 1.0
 */
open class ActivityDefaultInstaller : ActivityFrame() {

    private var apkFilePath = ""
    private var force = false

    override fun getIntentData(intent: Intent?) {
        super.getIntentData(intent)
        apkFilePath = intent?.getStringExtra("apkFilePath")?:""
        force = intent?.getBooleanExtra("force",false)?:false
    }

    override fun onInitStart() {
        if (apkFilePath.isNullOrEmpty()){
            finish()
            return
        }
        SoonPermission.with(this)
                .install(File(apkFilePath))
                .setPermissionListener(object : SimplePermissionListener() {
                    override fun onGranted() {
                        finish()
                    }
                    override fun onCancel() {
                        finish()
                    }

                    override fun onDenied(executor: RequestExecutor?, task: IPermissionTask?) {
                        rationale(executor)
                    }
                    override fun rationale(executor: RequestExecutor?): Boolean {
                        showDialog(executor)
                        return true
                    }
                })
                .start()
    }

    open fun showDialog(executor: RequestExecutor?){
        if (force){
            DialogAlert.create(activity)
                    .setMessage("您未允许安装未知来源应用，请在设置中开启后继续安装应用！")
                    .setConfirmListener { _, _ ->
                        executor?.execute()
                    }
                    .setConfirmText("去设置")
                    .setCancel(false)
                    .show()
        }else{
            DialogAlert.create(activity)
                    .setMessage("您未允许安装未知来源应用，请在设置中开启后继续安装应用！")
                    .setConfirmListener { _, _ ->
                        executor?.execute()
                    }
                    .setConfirmText("去设置")
                    .setCancelText("取消")
                    .setCancelListener { dialog, _ ->
                        dialog.dismiss()
                        finish()
                    }
                    .setCancel(false)
                    .show()
        }
    }

}